package dtec.project.whereareu;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;

public class MainInterface extends Activity {
	String DURL=MainActivity.URL+"/mapproject/insertlocation.php";
	Button send;
	UserData db;
	GPSTracker gps;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main_interface);
		gps = new GPSTracker(MainInterface.this);
		db=new UserData(this);
		send=(Button)findViewById(R.id.button1);
		send.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
	               // check if GPS enabled     
                if(gps.canGetLocation()){
                     
                    double latitude = gps.getLatitude();
                    double longitude = gps.getLongitude();
                    goSend(db.getUserID(),latitude,longitude);
                    // \n is for new line
                }else{
                    // can't get location
                    // GPS or Network is not enabled
                    // Ask user to enable GPS/network in settings
                    gps.showSettingsAlert();
                }
			}
		});
	}

	///function for login
	public void goSend(int uid,double la,double longti){

	//	Toast.makeText(Login.this,input[0].toString(), Toast.LENGTH_LONG).show();
		new letLogin().execute(String.valueOf(uid),String.valueOf(la),String.valueOf(longti));
	}
	
	//network class
	private class letLogin extends AsyncTask<String ,String ,String > {

		//get time
		private String getDateTime() {
	        SimpleDateFormat dateFormat = new SimpleDateFormat(
	                "yyyy-MM-dd HH:mm:ss", Locale.getDefault());
	        Date date = new Date();
	        return dateFormat.format(date);
	}
		@Override
		protected String doInBackground(String... params) {
			String urlparam = null;
			// TODO Auto-generated method stub
			try {
				urlparam=URLEncoder.encode("uid","UTF-8")+"="+URLEncoder.encode(params[0].toString(),"UTF-8");
				urlparam=urlparam+"&"+URLEncoder.encode("latitude","UTF-8")+"="+URLEncoder.encode(params[1].toString(),"UTF-8");
				urlparam=urlparam+"&"+URLEncoder.encode("longtitude","UTF-8")+"="+URLEncoder.encode(params[2].toString(),"UTF-8");
				urlparam=urlparam+"&"+URLEncoder.encode("date","UTF-8")+"="+URLEncoder.encode(getDateTime(),"UTF-8");
			} catch (UnsupportedEncodingException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			String s=sendHttpPost(urlparam,DURL);
			return s;
		}
	    protected void onPostExecute(String result) {
	    	//Login.flag=result;
	    	int a=0;
	    	try {
	    		JSONArray jarray=new JSONArray(result);
	    		for(int i=0;i<jarray.length();i++){
	    			JSONObject job=jarray.getJSONObject(i);
	    			a=job.getInt("uid");
	    		}
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
	    	Toast.makeText(MainInterface.this, "Updated", Toast.LENGTH_LONG).show();
	    	Intent intent=new Intent(MainInterface.this,MainActivity.class);
	    	finish();
	    	startActivity(intent);
	    }
	    public String sendHttpPost(String data,String u){
	    	String result=null;
	    	try {
				URL url=new URL(u);
				try {
					
					///set up
					HttpURLConnection cont=(HttpURLConnection)url.openConnection();
					cont.setRequestMethod("POST");
					cont.setConnectTimeout(6*1000);
					cont.setDoInput(true);
					cont.setDoOutput(true);
					cont.setUseCaches(false);
					
					///send
					DataOutputStream out=new DataOutputStream(cont.getOutputStream());
					out.writeBytes(data);
					out.flush();
					out.close();
					
					///get result
					InputStream in=cont.getInputStream();
					BufferedReader readin=new BufferedReader(new InputStreamReader(in,"UTF-8"));
					String line;
					StringBuffer respon=new StringBuffer();
					while((line=readin.readLine())!=null){
						respon.append(line);
						respon.append("\n");
					}
					readin.close();
					result=respon.toString();
					
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			} catch (MalformedURLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
	    	return result;
	    }
		
	}
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.activity_main_interface, menu);
		return true;
	}

}
